<template>
  <div class="live-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>直播列表</h2>
      <el-button type="default" @click="handleBack">返回</el-button>
    </div>

    <!-- 操作按钮区 -->
    <div class="operation-buttons">
      <el-button type="success" @click="openModal('add')">创建直播间</el-button>
      <el-button type="success" @click="openModal('add')">创建录播</el-button>
    </div>

    <!-- 筛选区域 -->
    <el-form inline :model="filterForm" class="filter-form">
      <el-form-item width="180px">
        <el-select v-model="filterForm.liveStatus" placeholder="直播状态" clearable style="width: 200px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="直播中" value="living"></el-option>
          <el-option label="未开始" value="pending"></el-option>
          <el-option label="已结束" value="ended"></el-option>
          <el-option label="禁播" value="ended"></el-option>
          <el-option label="暂停中" value="ended"></el-option>

        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select v-model="filterForm.displayStatus" placeholder="显示状态" clearable style="width: 200px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="显示" value="normal"></el-option>
          <el-option label="隐藏" value="hidden"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-input v-model="filterForm.keyword" placeholder="搜索直播标题/主播" clearable style="width: 200px"></el-input>
      </el-form-item>

      <el-form-item>
        <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" format="YYYY年MM月DD日" value-format="YYYY年MM月DD日"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 直播列表表格 -->
    <el-table :data="tableData" border stripe style="width: 100%; margin-top: 16px" :row-class-name="tableRowClassName">
      <el-table-column label="视频封面" width="120">
        <template #default="scope">
          <el-image :src="scope.row.coverUrl" :z-index="99999999" :preview-src-list="[scope.row.coverUrl]" fit="cover"
            style="width: 100px; height: 60px; border-radius: 4px"></el-image>
        </template>
      </el-table-column>

      <el-table-column prop="brand" label="品牌"></el-table-column>
      <el-table-column prop="brandCategory" label="品牌分类"></el-table-column>
      <el-table-column prop="weight" label="权重" width="80"></el-table-column>
      <el-table-column prop="title" label="直播标题"></el-table-column>
      <el-table-column prop="roomId" label="房间号"></el-table-column>
      <el-table-column prop="anchorNickname" label="主播昵称"></el-table-column>
      <el-table-column prop="videoName" label="视频名称"></el-table-column>
      <el-table-column prop="targetUsers" label="视频指定用户"></el-table-column>
      <el-table-column prop="videoType" label="视频形式"></el-table-column>
      <el-table-column prop="videoStatus" label="视频状态">
        <template #default="scope">
          <el-tag :type="scope.row.videoStatus === '正常' ? 'success' : 'info'">
            {{ scope.row.videoStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="视频开始时间"></el-table-column>
      <el-table-column prop="duration" label="视频时长"></el-table-column>
      <el-table-column prop="endTime" label="视频结束时间"></el-table-column>
      <el-table-column prop="anchorName" label="主播名称"></el-table-column>
      <el-table-column prop="viewCount" label="观看人数"></el-table-column>
      <el-table-column prop="likeCount" label="点赞"></el-table-column>

      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="primary"   @click="openModal('edit', scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" :width="600" destroy-on-close top="10vh">
      <el-form ref="liveFormRef" :model="formData" :rules="formRules" label-width="120px" size="default">
        <el-form-item label="直播类型" prop="liveType">
          <el-radio-group v-model="formData.liveType">
            <el-radio label="mobile">手机直播</el-radio>
            <el-radio label="camera">摄像头直播</el-radio>
          </el-radio-group>

        </el-form-item>
        <div class="form-hint  samil_application">通过“小程序直播”小程序开播</div>
        <el-form-item label="播放方式" prop="playType">
          <el-radio-group v-model="formData.playType">
            <el-radio label="h5">单播</el-radio>
            <el-radio label="web">web形式</el-radio>
          </el-radio-group>
          <div class="form-hint">单播：视频源比例为16:9、4:3、1:1、1:2.1；web形式：视频源比例为16:9、2.3</div>
        </el-form-item>

        <el-form-item label="直播间标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入直播间标题" maxlength="17"></el-input>
        </el-form-item>

        <el-form-item label="开播时间" prop="startTime">
          <el-date-picker v-model="formData.startTime" type="datetime" placeholder="选择开播时间"
            format="YYYY年MM月DD日 HH:mm:ss" value-format="YYYY年MM月DD日 HH:mm:ss"></el-date-picker>
          <div class="form-hint">开播时间可以修改，不变更直播都可以开播时间；直播需在预约的开始时间开播</div>
        </el-form-item>

        <el-form-item label="主播昵称" prop="anchorNickname">
          <el-input v-model="formData.anchorNickname" placeholder="请输入主播昵称" maxlength="15"></el-input>
        </el-form-item>

        <el-form-item label="视频指定用户" prop="targetUsers">
          <el-checkbox-group v-model="formData.targetUsers">
            <el-checkbox label="代理商"></el-checkbox>
            <el-checkbox label="美容院"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="视频封面" prop="coverUrl">
          <el-upload class="avatar-uploader" action="/upload" :show-file-list="false" :on-success="handleCoverUpload"
            accept="image/*">
            <img v-if="formData.coverUrl" :src="formData.coverUrl" class="cover-image">
            <el-button v-else type="success">选择文件</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="官方砍价" prop="bargainEnabled">
          <el-radio-group v-model="formData.bargainEnabled">
            <el-radio :label="true">开启</el-radio>
            <el-radio :label="false">关闭</el-radio>
          </el-radio-group>
          <div class="form-hint">开启后本直播间有可能被官方捞粉；此权限在直播前的状态都可以在控制台修改</div>
        </el-form-item>

        <el-form-item label="直播间状态" prop="videoStatus">
          <el-radio-group v-model="formData.videoStatus">
            <el-radio label="正常">正常</el-radio>
            <el-radio label="隐藏">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="success" @click="handleSave">下一步</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 筛选表单数据
const filterForm = reactive({
  liveStatus: '',
  displayStatus: '',
  keyword: '',
  dateRange: []
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 弹窗状态
const dialogVisible = ref(false)
const dialogType = ref('add')
const dialogTitle = ref('创建直播')

// 表单数据
const formData = reactive({
  id: '',
  liveType: 'mobile',
  playType: 'h5',
  title: '',
  startTime: '',
  anchorNickname: '',
  targetUsers: [],
  coverUrl: '',
  bargainEnabled: true,
  videoStatus: '正常'
})

// 表单验证规则
const formRules = reactive({
  title: [
    { required: true, message: '请输入直播间标题', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开播时间', trigger: 'change' }
  ],
  anchorNickname: [
    { required: true, message: '请输入主播昵称', trigger: 'blur' }
  ]
})

// 表单引用
const liveFormRef = ref(null)

// 模拟表格数据
const mockTableData = [
  {
    id: '1',
    coverUrl: 'https://picsum.photos/200/120?random=1',
    brand: 'GUCCI',
    brandCategory: '单品',
    weight: 1,
    title: '肌肤健康如此简单',
    roomId: '111236534',
    anchorNickname: 'GUCCI 单品',
    videoName: '肌肤健康如此简单01',
    targetUsers: '代理商、美容院',
    videoType: '录播',
    videoStatus: '正常',
    startTime: '2022年5月9日00:00:00',
    duration: '438分钟',
    endTime: '2022年5月9日03:00:00',
    anchorName: '李小叶',
    viewCount: 12231,
    likeCount: 1832
  },
  {
    id: '2',
    coverUrl: 'https://picsum.photos/200/120?random=2',
    brand: 'LV',
    brandCategory: '箱包',
    weight: 2,
    title: '夏季新品发布会',
    roomId: '111236535',
    anchorNickname: 'LV官方',
    videoName: '夏季新品发布会直播',
    targetUsers: '代理商',
    videoType: '直播',
    videoStatus: '正常',
    startTime: '2022年6月1日19:00:00',
    duration: '120分钟',
    endTime: '2022年6月1日21:00:00',
    anchorName: '张小明',
    viewCount: 25643,
    likeCount: 5678
  }
]

// 页面加载时获取数据
onMounted(() => {
  fetchTableData()
})

// 获取表格数据
const fetchTableData = () => {
  // 模拟接口请求
  tableData.value = mockTableData
  pagination.total = mockTableData.length
}

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row'
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
  ElMessage.success('搜索成功')
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.liveStatus = ''
  filterForm.displayStatus = ''
  filterForm.keyword = ''
  filterForm.dateRange = []
  pagination.currentPage = 1
  fetchTableData()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTableData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTableData()
}

// 返回
const handleBack = () => {
  window.history.back()
}

// 打开弹窗
const openModal = (type, row = null) => {
  dialogType.value = type
  dialogTitle.value = type === 'add' ? '创建直播' : '编辑直播'

  // 重置表单
  if (liveFormRef.value) {
    liveFormRef.value.resetFields()
  }

  // 编辑模式填充数据
  if (type === 'edit' && row) {
    formData.id = row.id
    formData.title = row.title
    formData.startTime = row.startTime
    formData.anchorNickname = row.anchorNickname
    formData.targetUsers = row.targetUsers.split('、')
    formData.coverUrl = row.coverUrl
    formData.videoStatus = row.videoStatus
  } else {
    // 新增模式重置数据
    formData.id = ''
    formData.liveType = 'mobile'
    formData.playType = 'h5'
    formData.title = ''
    formData.startTime = ''
    formData.anchorNickname = ''
    formData.targetUsers = []
    formData.coverUrl = ''
    formData.bargainEnabled = true
    formData.videoStatus = '正常'
  }

  dialogVisible.value = true
}

// 封面上传成功处理
const handleCoverUpload = (response, file, fileList) => {
  // 模拟上传成功
  formData.coverUrl = URL.createObjectURL(file.raw)
  ElMessage.success('封面上传成功')
}

// 保存表单
const handleSave = () => {
  liveFormRef.value.validate(async (valid) => {
    if (valid) {
      // 模拟接口请求
      if (dialogType.value === 'add') {
        // 新增逻辑
        const newItem = {
          id: Date.now().toString(),
          ...formData,
          brand: '未知品牌',
          brandCategory: '默认分类',
          weight: tableData.value.length + 1,
          roomId: '111' + Math.floor(Math.random() * 10000000),
          videoName: formData.title + '01',
          targetUsers: formData.targetUsers.join('、'),
          videoType: '直播',
          duration: '0分钟',
          endTime: '',
          anchorName: formData.anchorNickname,
          viewCount: 0,
          likeCount: 0
        }
        tableData.value.unshift(newItem)
        pagination.total = tableData.value.length
        ElMessage.success('创建成功')
      } else {
        // 编辑逻辑
        const index = tableData.value.findIndex(item => item.id === formData.id)
        if (index !== -1) {
          tableData.value[index] = {
            ...tableData.value[index],
            ...formData,
            targetUsers: formData.targetUsers.join('、')
          }
          ElMessage.success('编辑成功')
        }
      }
      dialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.live-management-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.operation-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.filter-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.form-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #606266;

}

.samil_application {
  margin-left: 120px;
  margin-bottom: 20px;
}

.cover-image {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

::v-deep .el-table .even-row {
  background-color: #f9f9f9;
}

::v-deep .el-table .odd-row {
  background-color: #fff;
}

::v-deep .el-dialog__body {
  max-height: 80vh;
  overflow-y: auto;
}
</style>